const { Video, VideoComment, VideoLikeSchema, Subscribe } = require('../model');
exports.list = (req, res) => {
  console.log(req.method);
  res.send('/video-list');
};

exports.likelist = async (req, res) => {
  const { videoId } = req.params;
  const { pageNum = 1, pageSize = 10 } = req.body;
  const likeList = await VideoLikeSchema.find({ video: videoId })
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .populate('video', '_id title vodvideoId user')
    .sort({ like: -1 });
  const likeCount = await VideoLikeSchema.countDocuments({ video: videoId });
  res.status(200).json({ likeList, likeCount });
};
// 处理喜欢或者不喜欢
const handleLikeStatus = async (userId, videoId, likeValue) => {
  let doc = await VideoLikeSchema.findOne({ user: userId, video: videoId });
  let isLike = true,
    isDislike = true;
  if (doc) {
    if (doc.like === likeValue) {
      await doc.deleteOne();
      likeValue === 1 && (isLike = false);
      likeValue === -1 && (isDislike = false);
    } else {
      doc.like = likeValue;
      await doc.save();
    }
  } else {
    await new VideoLikeSchema({ user: userId, video: videoId, like: likeValue }).save();
  }
  return { isLike, isDislike };
};
// 不喜欢视频
exports.dislikeVideo = async (req, res) => {
  const { videoId } = req.params;
  const userId = req.user.userinfo._id;
  const videoInfo = await Video.findById(videoId);
  if (!videoInfo) {
    return res.status(404).json({ err: '视频不存在' });
  }
  const { isDislike } = await handleLikeStatus(userId, videoId, -1);
  videoInfo.likeCount = await VideoLikeSchema.countDocuments({ video: videoId, like: 1 });
  videoInfo.dislikeCount = await VideoLikeSchema.countDocuments({ video: videoId, like: -1 });
  await videoInfo.save();
  return res.status(200).json({ ...videoInfo.toJSON(), isDislike });
};
// 喜欢视频
exports.likeVideo = async (req, res) => {
  const { videoId } = req.params;
  const userId = req.user.userinfo._id;
  const videoInfo = await Video.findById(videoId);
  if (!videoInfo) {
    return res.status(404).json({ err: '视频不存在' });
  }
  const { isLike } = await handleLikeStatus(userId, videoId, 1);
  videoInfo.likeCount = await VideoLikeSchema.countDocuments({ video: videoId, like: 1 });
  videoInfo.dislikeCount = await VideoLikeSchema.countDocuments({ video: videoId, like: -1 });
  await videoInfo.save();

  return res.status(200).json({ ...videoInfo.toJSON(), isLike });
};
// 删除评论
exports.deleteComment = async (req, res) => {
  const { videoId, commentId } = req.params;

  const videoInfo = await Video.findById(videoId);
  if (!videoInfo) {
    return res.status(404).json({ err: '视频不存在' });
  }

  const comment = await VideoComment.findById(commentId);
  if (!comment) {
    return res.status(404).json({ err: '评论不存在' });
  }

  // 不能直接使用==
  if (!comment.user.equals(req.user.userinfo._id)) {
    return res.status(403).json({ err: '评论不可删除' });
  }
  await comment.deleteOne();
  videoInfo.commentCount--;
  await videoInfo.save();
  return res.status(200).json({ msg: '删除成功' });
};
// 评论列表
exports.commentList = async (req, res) => {
  const { videoId } = req.params;
  const { pageNum = 1, pageSize = 10 } = req.body;
  const comments = await VideoComment.find({ video: videoId })
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .sort({ createTime: -1 })
    .populate('user', '_id username image');
  const commentCount = await VideoComment.countDocuments({ video: videoId });
  res.status(200).json({ comments, commentCount });
};
// 评论
exports.comment = async (req, res) => {
  const { videoId } = req.params;
  const videoInfo = await Video.findById(videoId);
  if (!videoInfo) {
    return res.status(404).json({ err: '视频不存在' });
  }
  const comment = await VideoComment({
    content: req.body.content,
    video: videoId,
    user: req.user.userinfo._id
  }).save();
  videoInfo.commentCount++;
  await videoInfo.save();
  res.status(200).json(comment);
};

// 视频入库
exports.createVideo = async (req, res) => {
  const body = {
    ...req.body,
    user: req.user.userinfo._id
  };
  const videoModel = new Video(body);
  try {
    const dbback = await videoModel.save();
    res.status(201).json({ dbback });
  } catch (error) {
    res.status(500).json({ err: error });
  }
};

// 视频列表
exports.getVideoList = async (req, res) => {
  const { pageNum = 1, pageSize = 10 } = req.body;
  // 分页处理
  const videoList = await Video.find()
    .skip((pageNum - 1) * pageSize)
    .limit(pageSize)
    .sort({ createAt: -1 }) // 降序
    .populate('user'); // 根据user获取用户信息

  const total = await Video.countDocuments();
  res.status(200).json({
    videoList,
    total,
    pageNum,
    pageSize
  });
};

// 视频详情
exports.videoDetail = async (req, res) => {
  const { videoId } = req.params;
  try {
    let videoInfo = await Video.findById(videoId).populate('user', '_id username cover'); // 返回user里的_id username cover并返回对象
    console.log('🚀 ~ exports.videoDetail= ~ videoInfo:', videoInfo);
    videoInfo = videoInfo.toJSON();
    videoInfo.isLike = false;
    videoInfo.isDislike = false;
    videoInfo.isSubscribe = false;
    if (req?.user?.userinfo) {
      const userId = req.user.userinfo._id;
      if (VideoLikeSchema.findOne({ video: videoId, user: userId, like: 1 })) {
        videoInfo.isLike = true;
      }
      if (VideoLikeSchema.findOne({ video: videoId, user: userId, like: -1 })) {
        videoInfo.isDislike = true;
      }
      if (Subscribe.findOne({ user: userId, channel: videoInfo.user._id })) {
        videoInfo.isSubscribe = true;
      }
    }
    res.status(200).json(videoInfo);
  } catch (error) {
    res.status(500).json({ err: error });
  }
};
